﻿var OfferModel = function (offers) {
    var self = this;
    self.currentItem = ko.observable('');
    self.sortDirection = ko.observable(true);
    self.offers = ko.observableArray(offers);
    self.columnNames = ko.observableArray([
            'Информация за шофьора:',
            'Тръгване от:',
            'Пристигане в:',
            'Дата',
            'Цена',
            //'Изтрий',
            //'Избери'
    ]);
    self.addOffer = function () {
        self.offers.push({
            driver: "",
            price: "",
            trip: "",
        });
    };

    self.removeOffer = function (offer) {
        self.offers.remove(offer);
    };

    self.sortColumn = function (item) {
        if (item == self.currentItem()) {
            self.sortDirection(!self.sortDirection())
        } else {
            self.currentItem(item);
            self.sortDirection(true)
        }
        if (self.sortDirection()) {
            var sorted = self.offers().sort();
            self.offers(sorted);
        } else {
            var sorted = self.offers().reverse();
            self.offers(sorted);
        }
    };

    self.printOffer = function (offer) {
        var div = document.createElement('div');
        div.innerHTML = offer.toString();
        document.body.appendChild(div);
    }
    self.save = function (form) {
        alert("Could now transmit to server: " + ko.utils.stringifyJson(self.offers));
        // To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0], self.offers);
    }
};

var get = new dbModule.Get();

get.offerByConditions(tripInfo, function (data) {

    var allOffers = [];
    for (var i = 0; i < data.length; i++) {
        var obj = new TripDetails.Offer(data[i].driver, data[i].price, data[i].trip);
        JSON.stringify(obj);
        allOffers.push(obj);
        allOffers.sort();
    }
    var viewModel = new OfferModel(allOffers);

    ko.applyBindings(viewModel);
});